package common

import (
	"database/sql"
	"go-scripts/config"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

var mysql *Mysql

type Mysql struct {
	Jingx *sql.DB
}

func connect(db string) *sql.DB {
	fmt.Println("初始化mysql")
	conf := config.GetConfig()
	mysqlConfig := conf.GetMysqlConfig()[db].(map[string]interface{})
	username := mysqlConfig["username"].(string)
	password := mysqlConfig["password"].(string)
	url := mysqlConfig["url"].(string)
	dbName := mysqlConfig["db"].(string)
	GetLogger().Info(fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", username, password, url, dbName))
	jingx, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", username, password, url, dbName))
	if err != nil {
		GetLogger().Fatal(err.Error(), "mysql加载失败")
	}
	return jingx
}

func GetMysql() *Mysql {
	if mysql != nil {
		return mysql
	}
	mysql = new(Mysql)
	mysql.Jingx = connect("jingx")
	return mysql
}